package com.asset.dispoal.extension.service;

import com.asset.dispoal.extension.api.PermissionExtensionService;
import com.asset.dispoal.extension.domain.dto.RolePermissionDTO;
import com.asset.dispoal.extension.dto.PermissionRequest;
import com.asset.dispoal.extension.service.command.PermissionRoleCommand;
import com.asset.dispoal.extension.strategy.DataPowerStrategyManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.strategy.StrategyHandlerParam;
import tech.mhuang.pacebox.core.strategy.StrategyHandlerResult;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.StringUtil;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Service
public class PermissionExtensionServiceImpl implements PermissionExtensionService {
    @Autowired
    private PermissionRoleCommand permissionRoleCommand;

    @Autowired
    private DataPowerStrategyManager dataPowerStrategyManager;


    @Override
    public String checkPermission(PermissionRequest permissionRequest) {
        List<RolePermissionDTO> dtoList = permissionRoleCommand.execute(permissionRequest);
        if (CollectionUtil.isEmpty(dtoList)) {
            throw new BusinessException("当前用户无权限访问");
        }
        //如果是0返回全部权限，
        if (StringUtil.equals("0", dtoList.get(0).getDataPowerCode()) || StringUtil.isBlank(dtoList.get(0).getDataPowerCode())) {
            return null;
        }

        List<String> sqlResultList = new CopyOnWriteArrayList<>();
        dtoList.forEach(dto -> {
            StrategyHandlerResult<String> result = dataPowerStrategyManager.strategy(new StrategyHandlerParam<>(dto.getDataPowerCode(), dto));
            if (result.isStatus()) {
                sqlResultList.add(result.getData());
            }
        });

        if (CollectionUtil.isNotEmpty(sqlResultList)) {
            for (int i = 0; i < sqlResultList.size(); i++) {
                if (i == 0) {
                    sqlResultList.set(i, "EXISTS (" + sqlResultList.get(i) + ")");
                } else {
                    sqlResultList.set(i, " or EXISTS (" + sqlResultList.get(i) + ")");
                }
            }
        }
        return StringUtil.join(sqlResultList, " ");
    }
}
